package com.springboot.demo.config;

import com.springboot.demo.annotation.DataSource;
import com.springboot.demo.enums.DataBaseKindEnum;
import com.springboot.demo.enums.DataSourceEnum;
import com.springboot.demo.enums.SlaveEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;

@Component
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {

    private static final SecureRandom RANDOM = new SecureRandom();

    private static <T extends Enum<?>> T randomEnum(Class<T> clazz){
        int x = RANDOM.nextInt(clazz.getEnumConstants().length);
        return clazz.getEnumConstants()[x];
    }

    @Pointcut("@within(com.springboot.demo.annotation.DataSource) || @annotation(com.springboot.demo.annotation.DataSource)")
    public void pointCut(){

    }

    @Before("pointCut() && @annotation(dataSource)")
    public void doBefore(DataSource dataSource){
        log.info("选择数据源---"+dataSource.value().getValue());
        if(DataBaseKindEnum.MASTER.equals(dataSource.value().getValue())){
            log.info("主数据源:db1");
            DataSourceContextHolder.setDataSource(DataSourceEnum.DB1.getValue());
        }else if(DataBaseKindEnum.SLAVE.equals(dataSource.value().getValue())){
            String db = randomEnum(SlaveEnum.class).getValue();
            log.info("次数据源："+db);
            DataSourceContextHolder.setDataSource(db);
        }

    }

    @After("pointCut()")
    public void doAfter(){
        DataSourceContextHolder.clear();
    }
}